package com.nuanshui.heatedloan.userinfo.service;

import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.userinfo.constant.IntegralActionType;
import com.nuanshui.heatedloan.userinfo.facade.UserActionService;
import com.nuanshui.heatedloan.userinfo.facade.UserIntegralService;
import com.nuanshui.heatedloan.userinfo.model.SimpleUserInfo;
import com.nuanshui.heatedloan.userinfo.model.User;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import com.nuanshui.heatedloan.userinfo.vo.IncrUserIntegralVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;


@Service("userActionService")
@Transactional(readOnly=true,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
public class UserActionServiceImpl implements UserActionService {

	@Autowired
	private UserTool userTool;
	@Autowired
	private UserIntegralService userIntegralService;
	
	@Autowired
	private JedisUtil jedisUtil;
	
	/**
	 * 用户签到
	 */
	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public IncrUserIntegralVo sign() {
		IncrUserIntegralVo incrUserIntegralVo =  userTool.incrUserIntegral(IntegralActionType.SIGN);		
		Calendar calendar = Calendar.getInstance();	
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		String date = 	DateUtil.format(calendar.getTime(),"yyyy-MM-dd");
		Integer time = userIntegralService.getContinuousTime(IntegralActionType.SIGN, date);
		User user = userTool.getCurrentUser();
		if(time == null) time = 0;
	    if(incrUserIntegralVo.getScore() !=0) {
	    	SimpleUserInfo simpleUserInfo = userTool.getSimpleUserInfo(user.getId());
			simpleUserInfo.setScore(simpleUserInfo.getScore()+time*1);
	    	incrUserIntegralVo.setAcquireScore(incrUserIntegralVo.getScore()+time*1);
	    	incrUserIntegralVo.setLevel(userTool.parseUserLevel(simpleUserInfo.getScore()));
			incrUserIntegralVo.setNextScore(incrUserIntegralVo.getAcquireScore()+1);
			jedisUtil.setObject(GlobalParam.USER_PREFIX+user.getId(), simpleUserInfo);
			userIntegralService.updateUserTotalIntegral(user.getId(), (double)time*1);
	    }
	    
	    return incrUserIntegralVo;
		
	}



}
